#!/bin/bash

set -e
cur_path=$(pwd)

echo "start to prepare version check env"
chmod +x /root/repo/ci-repos/.common_scripts/common.sh
source /root/repo/ci-repos/.common_scripts/common.sh
set_gitee_hosts
prepare_git $1 $2


cd ${cur_path}

function handle_error() {
    local exit_code=$?
    echo "Error occurred in script at line: ${1} with exit code: ${exit_code}"
    exit $exit_code
}

trap 'handle_error ${LINENO}' ERR


function get_comp_ver()
{
    comp_ver=$(head mds/service.json | grep version | awk 'NR==1'| awk -F: '{print $2}' \
        | awk -F\" '{print $2}')||:
    echo "comp_ver $comp_ver"
    export comp_ver
}

function check_lastest_tag()
{
    check_tag_ret=0
    lastest_tag=$(git log --simplify-by-decoration --decorate --pretty=oneline | grep 'tag: ' \
        | sed -n 's/^.*tag:[ ]\([0-9]*.[0-9]*.[0-9]*\).*/\1/p' | head -1)
    echo "start to check lastest tag............."
    if [ -n "${lastest_tag}" ]; then
        read -r -a now <<< "${comp_ver//./ }"
        read -r -a last <<< "${lastest_tag//./ }"
        lastnum=$((last[0]*1000*1000+last[1]*1000+last[2]))
        nownum=$((now[0]*1000*1000+ now[1]*1000+ now[2]))
        if [ ${lastnum} -ge ${nownum} ]; then
            echo "[error]: 组件发布后不变更版本号拒绝合入。当前组件的版本号${comp_ver}小于等于\
            最新发布版本号${lastest_tag}，请刷新组件版本号，避免组件发布时失败。"
            review_str=${review_str}"【门禁--组件发布后不变更版本号拒绝合入】检查结果：不通过。"
            check_tag_ret=1
        fi
    fi
    echo " check_tag_ret $check_tag_ret"
    export check_tag_ret
}

function check_increasing ()
{
    check_incre_ret=0
    old_version=$(git diff HEAD~1 -- mds/service.json | grep \"version\": | grep - | awk -F\" '{print $4}')
    new_version=$(git diff HEAD~1 -- mds/service.json | grep \"version\": | grep + | awk -F\" '{print $4}')
    echo "start to check increasing version..............."
    if [ -n "${old_version}" ] && [ -n "${new_version}" ]; then
        read -r -a now <<< "${new_version//./ }"
        read -r -a last <<< "${old_version//./ }"
        lastnum=$((last[0]*1000*1000+last[1]*1000+last[2]))
        nownum=$(( now[0]*1000*1000+ now[1]*1000+ now[2]))
        echo "lastnum: $lastnum"
        echo "nownum: $nownum"
        if [ ${lastnum} -gt ${nownum} ]; then
            echo "[ERROR]: 组件版本拒绝回退。当前组件的版本号${new_version}小于\
            修改前版本号${old_version}，请向committer确认版本号是否正确！"
            review_str=${review_str}"【门禁--组件版本拒绝回退】检查结果：不通过。"
            check_incre_ret=1
        fi
    fi
    echo "check_incre_ret $check_incre_ret"
    export check_incre_ret
}

function check_comp_version()
{
    echo "start to check version.........."
    get_comp_ver
    check_lastest_tag
    check_increasing
}

check_comp_version

if [ ! $check_tag_ret -eq 0 ]; then
    exit 1
fi
if [ ! $check_incre_ret -eq 0 ]; then
    exit 1
fi